package com.cntcdt.api.db.dao;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cntcdt.api.db.dao.base.ShopDaoBase;
import com.cntcdt.api.db.model.ShopModel;
import com.cntcdt.api.utils.LogUtils;
import com.cntcdt.api.utils.ReflectUtils;
import com.coola.jutil.sql.DBEngine;
import com.coola.jutil.sql.DBFactory;

/**
 * 这是cdt_shop的Dao实现类
 */
public class ShopDao extends ShopDaoBase   {
    /**
     * ShopDao对象
     */
    private static ShopDao instance = new ShopDao();

    /**
     * 默认构造方法
     */
    private ShopDao() {
    }

    /**
     * 获得对象实例
     */
    public static ShopDao getInstance() { 
         return instance;
    } 

    /**
     * 插入一条数据
     * @param  model UserModel对象
     * @return 返回插入影响行数
     */
    public int insertModel(Object model) {
        DBEngine localEngine = DBFactory.getKeepConnDBEngine("main");
        StringBuffer sql = new StringBuffer("INSERT INTO " + TABLE + " (");
        StringBuffer stmts =  new StringBuffer(" values(");
        List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = model.getClass().getSuperclass().getDeclaredFields();
//		Field[] fields = userModel.getClass().getDeclaredFields();
		for(Field field : superfields){
			if(field.getName().equals("serialVersionUID") || field.getName().equals("id")){
				continue;
			}
			if(ReflectUtils.getter(model, field.getName())!=null){
				sql.append(" "+field.getName()+",");
				stmts.append("?,");				
				sqlArgs.add(ReflectUtils.getter(model, field.getName()));
			}
		}
		
		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length()-1);
		sqlstr = sqlstr + ")";
		
		String stmtstr = stmts.toString();
		stmtstr = stmtstr.substring(0, stmtstr.length()-1);
		stmtstr = stmtstr + ")";
        
		LogUtils.log.info(sqlstr + stmtstr);
		
		Object[]  paramObj = sqlArgs.toArray();
        int id=0;
        try {
        	String tSql = sqlstr+stmtstr;
             id = localEngine.executeUpdate(tSql, paramObj);
             ResultSet rs = localEngine.executeQuery("select last_insert_id() as id");
             if (rs.next()) {
               id = rs.getInt("id");
             }
        }catch(Exception e) {
           e.printStackTrace();
        } finally {
           localEngine.close();
        }
        return id;
    }
    

    /**
     * 更新操作，自动根据userModel中已经设置的字段进行更新
     * 必须要设置userModel.id属性 和 其他任意一个属性
     * 
     * 返回更新结果
     */
    public boolean updateAny(Object model){
    	StringBuffer sql = new StringBuffer("update  "+TABLE+" set ");
		List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = model.getClass().getSuperclass().getDeclaredFields();
//		Field[] fields = userModel.getClass().getDeclaredFields();
		for(Field field : superfields){
			if(field.getName().equals("serialVersionUID") || field.getName().equals("id")){
				continue;
			}
			if(ReflectUtils.getter(model, field.getName())!=null){
				sql.append(" "+field.getName()+"=? ,");
				sqlArgs.add(ReflectUtils.getter(model, field.getName()));
			} 
		}
		
		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length()-1);
		sqlstr = sqlstr + " where id=?";
		sqlArgs.add(ReflectUtils.getter(model,"id"));
		LogUtils.log.info(sqlstr);
		LogUtils.log.info(sqlArgs.toString());
		
		Object[]  paramObj = sqlArgs.toArray();
        try {
             return writeDBEngine.executeUpdate(sqlstr, paramObj)>0;
        } catch(Exception e) {
           e.printStackTrace();
        }
        return false;
    }
    
    
    /**
     * 获得model集合
     * @return 返回Model集合
     */
    public List<ShopModel> findBySortTime( long sortTime , int limit) {
        String sql = "SELECT * FROM " + TABLE + " where sortTime<? order by sortTime desc limit ? " ;
        return queryModelList(sql , new Object[]{sortTime,limit});
    }
    
    /**
     * 根据地区名称查询
     * @param area
     * @return
     */
    public List<ShopModel> findByArea(String area){
    	String sql = "SELECT * FROM " + TABLE + " where address like '%?%'" ;
    	LogUtils.log.info(sql);
        return queryModelList(sql , new Object[]{area});
    }
    
    /**
     * 查询指定ID之后的model
     * @param sortTime
     * @param limit
     * @return
     */
    public List<ShopModel> findByBeforeId(int id) {
        String sql = "SELECT * FROM " + TABLE + " where id>? " ;
        return queryModelList(sql , new Object[]{id});
    }
    
    /**
     * 分页查询数据
     * @param sortTime
     * @param limit
     * @return
     */
    public List<ShopModel> findByPage(int sortTime) {
    	sortTime = sortTime*20;
        String sql = "SELECT * FROM " + TABLE + " limit ?,20" ;
        return queryModelList(sql , new Object[]{sortTime});
    }  
    
    /**
     * 搜索查询
     * @param sortTime
     * @param limit
     * @return
     */
    public List<ShopModel> findBySearchContent(String searchContent,int sortTime) {
    	sortTime = sortTime*20;
        String sql = "SELECT * FROM " + TABLE + " WHERE name LIKE ? limit ?,20" ;
        return queryModelList(sql , new Object[]{searchContent,sortTime});
    }  
    
}
